using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using Microsoft.CommerceServer.Marketing;

namespace BulkInsertCoupons
{
	/// <summary>
	/// A command line tool for automating migration\bulk inserting coupons.
	/// </summary>
	class Startup
	{
		/// <summary>
		/// The main entry point for the application.
		/// Two arguments are passed in order to function correctly:
		/// 1. A database connection string to access coupons to create.
		/// 2. Marketing Web Service address
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			if(args.Length==2)
			{
				// if we have 2 command line args then connect to the database
				// and insert coupons

				// The first argument is the database connection string.
				string DBConnectionString = args[0].ToString();
				// The second argument is the Marketing Web Service URL.
				string CouponWebService = args[1].ToString();

				// this sql command needs to have the following fields.
				// campaignID
				// discountName
				// startDate
				// endDate
				// BasketDisplay
				// Comments
				// DiscountType
				// productID
				// AmountOff
				// OrderLimit
				// expressions
				string sql = "Select * from couponmigration";

				SqlConnection cn = new SqlConnection(DBConnectionString);
				cn.Open();
				SqlCommand cmd = new SqlCommand(sql, cn);
				SqlDataReader rdr = cmd.ExecuteReader();

				while (rdr.Read())
				{
					try
					{
						// set values
						int campaignID = Convert.ToInt32(rdr[0]);
						string discountName = rdr[1].ToString();
						DateTime startDate = Convert.ToDateTime(rdr[2]);
						DateTime endDate = Convert.ToDateTime(rdr[3]);
						string BasketDisplay = rdr[4].ToString();
						string Comments = rdr[5].ToString();
						string DiscountType = rdr[6].ToString();
						string productID = rdr[7].ToString();
						string catalogName = rdr[8].ToString();
						string AmountOff = rdr[9].ToString();
						int OrderLimit = Convert.ToInt32(rdr[10]);
						int expressions = Convert.ToInt32(rdr[11]);

						// temporary string
						StringBuilder tmpBuilder = new StringBuilder();

						// connect to the marketing web service
						MarketingSystem mktSystem = new MarketingSystem(CouponWebService);
						
						// create a expresion manager for inserting (award expression, eligibility requirement etc...)
						ExpressionManager expressionManager = mktSystem.Expressions;
						// create a discount manager to create new discounts
						CampaignItemManager discountManager = mktSystem.CampaignItems;
						// current disocount to work with
						Discount newDiscount = (Discount)discountManager.NewCampaignItem(typeof(Discount),campaignID);
				
						//******************************************************
						// Populate new discount properties
						//******************************************************
						newDiscount.Name = discountName;
						newDiscount.StartDate = startDate;
						newDiscount.EndDate = endDate;
						newDiscount.BasketDisplay = BasketDisplay;
						newDiscount.Description = Comments;
						newDiscount.DiscountType = Microsoft.CommerceServer.Marketing.DiscountType.LineItem;
						//******************************************************

						//******************************************************
						// Setting AwardExpression expression
						//******************************************************
						Expression productExpression = expressionManager.NewExpressionFromProductPickerProduct(catalogName, productID, true);
						productExpression.Category = "CatalogCondition";
						productExpression.Description = productID;

						tmpBuilder.Append(newDiscount.Id);
						tmpBuilder.Append("_EXPR_");
						tmpBuilder.Append(Guid.NewGuid().ToString());

						productExpression.Name = tmpBuilder.ToString();

						// Clearing temporary string builder
						tmpBuilder.Remove(0, tmpBuilder.Length);

						newDiscount.AwardExpression = expressionManager.NewExpressionRef(productExpression);
						//******************************************************

						newDiscount.Condition.Basis = ConditionBasis.Quantity;
						newDiscount.Condition.MinimumAmount = 0;
						newDiscount.OfferType = OfferType.Currency;
						newDiscount.OfferAmount = Convert.ToDecimal(AmountOff);
						newDiscount.PerOrderLimit = 0;
						newDiscount.MaxAwards = 1;

						//******************************************************
						// Setting eligibility expression
						//******************************************************
						ExpressionRef selectedExpref = mktSystem.Expressions.NewExpressionRef(expressions);

						newDiscount.EligibilityRequirements.Add(selectedExpref);
						//******************************************************

						newDiscount.Save(true);
					}
					catch(Exception Ex)
					{
						// display error
						Console.WriteLine(Ex.Message);
					}
				}
				
				rdr.Close();
				cn.Close();
			}
			else
			{
				// if no args passed then show usage command
				Console.WriteLine("Need to enter database connection string and\\or Coupons web service connection.");
				Console.WriteLine("BulkInsert.exe MyDBConnectionstring MyWebService");
			}
		}
	}
}
